#include "config.h"

#include "ecm.h"

ECMBOOL		is_daemon;
static char	*daemon_clxdir;
static char	*daemon_name;

static void
create_pidfile(const char *clxdir, const char *name)
{
	FILE	*fp;
	char	*pidfile;

	ecm_asprintf(&pidfile, "%s/log/%s.pid", clxdir, name);
	fp = fopen(pidfile, "w+");
	if (fp) {
		fprintf(fp, "%d", getpid());
		fclose(fp);
	}
	ecm_free(pidfile);
}

static void
remove_pidfile(const char *clxdir, const char *name)
{
	char	*pidfile;

	ecm_asprintf(&pidfile, "%s/log/%s.pid", clxdir, name);
	unlink(pidfile);
	ecm_free(pidfile);
}

void
ecm_daemon_check(const char *name, const char *desc, const char *deps,
		 int (*_main_func)(int, char **, char **),
		 int argc, char *argv[])
{
	/* Nothing */
}

void
ecm_daemon_reg_stopper(ecm_daemon_stopper_t stopper, ecm_ptr_t ctx)
{
	/* Nothing */
}

void
ecm_daemonize(const char *clxdir, const char *name)
{
	pid_t	pid;
	int	fds[2];

	is_daemon = ECM_TRUE;
	daemon_clxdir = ecm_strdup(clxdir);
	daemon_name = ecm_strdup(name);

	pipe(fds);
	close(0);
	close(1);
	dup2(fds[0], 0);
	dup2(fds[1], 1);
	close(fds[0]);
	close(fds[1]);
	pid = fork();

	if (pid > 0) {
		ecm_uint8	buf[128];

		close(1);
		if (read(0, buf, 128) != 128)
			exit(255);
		if (buf[0] != 0)
			fprintf(stderr, "%s\n", buf + 1);
		exit((int)buf[0]);
	}
	else if (pid < 0)
		exit(255);

	close(0);
	close(2);
	setsid();

	create_pidfile(clxdir, name);
}

void
ecm_daemon_cleanup(void)
{
	if (is_daemon)
		remove_pidfile(daemon_clxdir, daemon_name);
}

void
ecm_daemon_exit(ecm_uint8 exitcode, const char *fmt, ...)
{
	char	buf[128];

	if (!is_daemon)
		return;

	if (fmt) {
		va_list	ap;
		
		va_start(ap, fmt);
		vsnprintf(buf + 1, 127, fmt, ap);
		va_end(ap);
	}
	buf[0] = exitcode;
	write(1, buf, 128);
}

void
ecm_daemon_set_running(void)
{
	if (is_daemon) {
		ecm_uint8	buf[128];
		buf[0] = 0;
		write(1, buf, 128);
		close(1);
	}
}
